/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.shiro.realm;

import com.arisgo.cloud.shiro.jwt.JwtToken;
import com.arisgo.cloud.shiro.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.lang.util.StringUtils;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Arisgo
 * @since 2024/1/23
 */
public class ShiroRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String secret = "secret";
    private final long TIME_UNIT = 10000;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权信息
     *
     * @param principals
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取当前登陆账号
        String userId = "";
        SimpleAuthorizationInfo authorization = new SimpleAuthorizationInfo();
        // 设置角色
        authorization.addRole("");
        // 设置权限
        authorization.addStringPermission("");

        return authorization;
    }

    /**
     * 身份验证
     *
     * @param token
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwt = token.getPrincipal().toString();
        if (!StringUtils.hasLength(jwt)) {
            logger.warn("jwt为空！");
            throw new RuntimeException();
        }
        if (!JWTUtil.verify(jwt, secret)) {
            logger.warn("token异常！");
            throw new RuntimeException();
        }
        String userId = JWTUtil.getClaim(jwt, "userId").asString();
        return new SimpleAuthenticationInfo(userId, token, this.getName());
    }

}
